package com.stenio.fancat.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.domain.Activity;
import com.stenio.fancat.domain.Brand;
import com.stenio.fancat.form.BrandForm;
import com.stenio.fancat.mapper.BrandMapper;
import com.stenio.fancat.util.StringUtil;

/**
 * 品牌模块服务实现类
 * @author stenio
 */
@Service
public class BrandService extends ServiceImpl<BrandMapper, Brand> {

	@Autowired
	private BrandMapper brandMapper;
	@Autowired
	private ActivityService activityService;

	/**
	 * 通过品牌名称模糊查询品牌列表
	 * 
	 * @param brandName
	 *            品牌名称
	 * @return 品牌列表
	 */
	public List<Brand> queryBrandByLikeName(BrandForm brandForm) {
		if (null == brandForm || StringUtils.isBlank(brandForm.getBrandName())) {
			return null;
		}
		return selectList(new EntityWrapper<Brand>().like(Brand.BRAND_NAME, brandForm.getBrandName()));
	}

	/**
	 * 通过品牌名称查询品牌列表
	 * 
	 * @param brandName
	 *            品牌名称
	 * @return 品牌列表
	 */
	public List<Brand> queryBrandByName(String brandName) {
		if (StringUtil.isEmpty(brandName)) {
			return null;
		}
		return selectList(new EntityWrapper<Brand>().eq(Brand.BRAND_NAME, brandName));
	}

	/**
	 * 分页查询品牌列表
	 * 
	 * @param 每页显示条数，size
	 * @param current当前页
	 */
	public Page<Brand> queryBrandPage(BrandForm brandForm) {
		if (null == brandForm) {
			throw new RuntimeException("参数不能为空");
		}
		Page<Brand> page = new Page<Brand>(brandForm.getCurrentPageNo(), brandForm.getPageSize());
		EntityWrapper<Brand> ew = new EntityWrapper<Brand>();
		ew.orderBy(Brand.BRAND_ID, false);
		// 获取品牌
		Page<Brand> resultPage = selectPage(page, ew);
		List<Brand> brands = resultPage.getRecords();
		for (Brand b : brands) {
			List<Activity> acts = activityService
					.selectList(new EntityWrapper<Activity>().eq(Activity.BRAND_ID, b.getBrandId()));
			int candyCount = 0;
			// 通过品牌获取活动列表，并统计总额
			for (int i = 0; i < acts.size(); i++) {
				Activity t = acts.get(i);
				candyCount = candyCount + t.getTotleCandy();
			}
			b.setActivityCount(acts.size());
			b.setBrandCandy(candyCount);
		}
		resultPage.setRecords(brands);
		return resultPage;
	}

	/**
	 * 保存品牌
	 * 
	 * @param brand
	 */
	public void saveBrand(Brand brand) {
		if (null == brand || StringUtils.isBlank(brand.getBrandName())) {
			throw new RuntimeException("品牌名称不能为空");
		}
		brandMapper.insertSelective(brand);
	}

}
